<template>
  <!-- 指标组件 -->
  <div class="ranking" v-loading="loading">
    <div class="ranking-title">
      <span>{{ data.name }}</span>
    </div>
    <div class="ranking-date">
      <!-- 日期 -->
      <p v-if="screenTime && screenTime.length != 0">
        <span class="left">{{ new Date(screenTime[0]).format("yyyy-MM-dd") }} ~ {{ new Date(screenTime[1]).format("yyyy-MM-dd") }}</span>
      </p>
      <p v-else>
        <span v-if="data.relativelyTime || data.relativelyTime == 0" class="left">{{ relativelyTimeDeal.format("yyyy-MM-dd") }} ~ {{ new Date().format("yyyy-MM-dd") }}</span>
        <span v-else class="left">{{ new Date(data.startTime).format("yyyy-MM-dd") }} ~ {{ new Date(data.endTime).format("yyyy-MM-dd") }}</span>
      </p>
      <!-- el-tooltip -->
      <p class="tooltip-p" v-if="screenTime && screenTime.length != 0">
        <el-tooltip content="筛选时段" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
      </p>
      <p class="tooltip-p" v-else>
        <el-tooltip v-if="data.relativelyTime || data.relativelyTime == 0" :content="`统计时段 相对${ data.relativelyTime/3600/1000/24 == 0 ? '今' : data.relativelyTime/3600/1000/24 }天时段`" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
        <el-tooltip v-else content="统计时段 固定时段" placement="bottom" effect="light">
          <img class="right" :src="dateIcon" alt="">
        </el-tooltip>
      </p>
    </div>
    <div class="ranking-echartsTitle">
      <span class="left"></span>
      <span class="right"></span>
    </div>
    <!-- echarts -->
    <div v-if="payloadData.dayData && payloadData.dayData.length != 0" :id="'rankingCharts' + id" class="ranking-echarts" style="width: 100%;height: 272px;"></div>
    <!-- empty -->
    <el-empty v-else :image="emptyImg" description="暂无数据" :image-size="80" style="width: 100%;height: 272px;"></el-empty>
  </div>
</template>

<script>
// vuex
import store from "@/store";
// 图片
import * as echarts from 'echarts';
import dateIcon from '@/assets/dataCenter/dataB_dateIcon.png';
import emptyImg from '@/assets/dataCenter/dataB_empty.png';
// API
import {
  dataBoardByChartId,
  merchantReportGetChartDataSort
} from '@/api/dataCenter/dataBoard.js';
// utils
import { dateStrChangeTimeTamp } from './utils.js'
export default {
  name: 'Ranking',
  components: {},
  props: {
    id: {
      type: Number,
      default: () => {
        return null;
      }
    }
  },
  data() {
    return {
      loading: false,
      dateIcon,
      emptyImg,
      data: {},
      payloadData: {},
      relativelyTimeDeal: null,
    }
  },
  watch: {
    screenTime: {
      handler(val) {
        this.merchantReportGetChartDataSortApi();
      },
      deep: true
    },
    organizationId: {
      handler(val) {
        this.merchantReportGetChartDataSortApi();
      },
      deep: true
    }
  },
  mounted() {
    this.dataBoardByChartIdApi();
  },
  methods: {
    // 获取报表数据
    async dataBoardByChartIdApi() {
      let res = await dataBoardByChartId({
        id: this.id
      });
      if(res.code === 200) {
        this.data = res.payload;
        let start = new Date()
        start.setTime(start.getTime() - this.data.relativelyTime)
        this.relativelyTimeDeal = start;
        if(this.data.relativelyTime === 0) {
          this.relativelyTimeDeal = new Date();
        }
        // 获取chart数据
        this.merchantReportGetChartDataSortApi();
      }
    },
    // 获取报表具体数据
    async merchantReportGetChartDataSortApi() {
      this.loading = true;
      let startTime;
      let endTime;
      let screenTime = store.state.user.screenTime;
      if(screenTime && screenTime.length != 0) {
        startTime = dateStrChangeTimeTamp(screenTime[0]);
        endTime = dateStrChangeTimeTamp(screenTime[1]);
      } else {
        // startTime 和 endTime存在即固定时间
        if(this.data.startTime && this.data.endTime) {
          startTime = this.data.startTime;
          endTime = this.data.endTime;
        }
        // relativelyTime存在即相对时间
        if(this.data.relativelyTime) {
          let nowDate = new Date().getTime();
          let startDate = nowDate - this.data.relativelyTime;
          startTime = startDate;
          endTime = nowDate;
        }
      }
      let res = await merchantReportGetChartDataSort({
        id: this.id,
        startTime,
        endTime,
        insId: store.state.insId.insId,
        toIndex: this.data.size == 1 ? 5 : 10
      })
      if(res.code === 200) {
        this.payloadData = res.payload;
        if(this.payloadData && this.payloadData.dayData.length != 0)  {
          this.capsulationDealData(0);
        } else {
          this.loading = false;
        }
      }
    },
    // 封装处理数据
    capsulationDealData() {
      let dataKeyName;
      let dataValueName;
      let ydata = [];
      let xdata = [];
      if(this.payloadData.groupColumn && this.payloadData.groupColumn.indexOf('columnHumpName') != -1) {
        // 分组
        let groupColumn = JSON.parse(this.payloadData.groupColumn.replace(/\\/g, ''));
        dataValueName = groupColumn[0].columnHumpName;
        if(this.payloadData.specialColumn && this.payloadData.specialColumn.indexOf(',') === -1) {
          // 单指标
          let specialColumn = this.payloadData.specialColumn.replace('{', '').replace('}', '').split('=');
          dataKeyName = specialColumn[0];
          this.payloadData.dayData.forEach(item => {
            ydata.push(item.groupColumn);
            xdata.push(item.data);
          });
        }
      }
      ydata.reverse();
      xdata.reverse();
      this.loading = false;
      this.$nextTick(() => {
        if(this.payloadData.dayData.length != 0) {
          this.drawCharts(ydata, xdata);
        }
      })
    },
    drawCharts(ydata, xdata) {
      let myChart = echarts.init(document.getElementById('rankingCharts' + this.id));
      // let ydata = ['数据7', '数据6', '数据5', '数据4', '数据3', '数据2', '数据1'];
      // let xdata = [ 116, 117, 118, 119, 420, 521, 529];
      let option = {
        tooltip: {
          trigger: "axis",
        },
        grid: {
          left: "80",
          right: "20",
          bottom: "0",
          top: "0",
          containLabel: false,
        },
        xAxis: {
          type: "value",
          show: false,
        },
        yAxis: {
          type: "category",
          data: ydata,
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
          },
          axisLabel: {
            margin: 70,
            width: 70,
            align: "left",
            overflow: "truncate",
            formatter: function (value, index) {
              let ind = index + 1;
              if (ind == ydata.length) {
                return "{one|" + (ydata.length - index) + "} {a|" + value + "}";
              } else if (ind + 1 == ydata.length) {
                return "{two|" + (ydata.length - index) + "} {b|" + value + "}";
              } else if (ind + 2 == ydata.length) {
                return (
                  "{three|" + (ydata.length - index) + "} {c|" + value + "}"
                );
              }
              if (ydata.length - index > 9) {
                return (
                  "{five|" + (ydata.length - index) + "} {d|" + value + "}"
                );
              }
              return "{four|" + (ydata.length - index) + "} {d|" + value + "}";
            },
            rich: {
              a: {
                color: "#59c9f9",
              },
              b: {
                color: "#59c9f9",
              },
              c: {
                color: "#59c9f9",
              },
              d: {
                color: "#59c9f9",
              },
              // 第一名
              one: {
                backgroundColor: "#E86452",
                color: "white",
                width: 12,
                height: 16,
                padding: [1, 0, 0, 5],
                borderRadius: 10,
                fontSize: 11,
              },
              // 第二名
              two: {
                backgroundColor: "#FF9845",
                color: "white",
                width: 12,
                height: 16,
                padding: [1, 0, 0, 5],
                borderRadius: 10,
                fontSize: 11,
              },
              // 第三名
              three: {
                backgroundColor: "#F6BD16",
                color: "white",
                width: 12,
                height: 16,
                padding: [1, 0, 0, 5],
                borderRadius: 10,
                fontSize: 11,
              },
              // 一位数
              four: {
                backgroundColor: "rgba(0,0,0,0.15)",
                color: "white",
                width: 12,
                height: 16,
                padding: [1, 0, 0, 5],
                borderRadius: 10,
                fontSize: 11,
              },
              // 两位数
              five: {
                backgroundColor: "rgba(0,0,0,0.15)",
                color: "white",
                width: 16,
                height: 16,
                padding: [1, 0, 0, 1],
                borderRadius: 10,
                fontSize: 11,
              },
            },
          },
        },
        series: [{
          type: "bar",
          showBackground: true,
          label: {
            show: true,
            position: "right",
            color: "rgba(0,0,0,0.45)",
          },
          barWidth: 20,
          itemStyle: {
            color: "#5B8FF9",
          },
          data: xdata,
        }, ],
      };
      myChart.setOption(option);
      window.addEventListener('resize', () => {
        if(myChart) myChart.resize();
      })
    }
  },
  computed: {
    screenTime() {
      return store.state.user.screenTime;
    },
    organizationId() {
      return store.state.insId.insId;
    }
  }
}
</script>

<style lang="scss" scoped>
.ranking {
  width: 100%;
  height: 100%;
  &-title {
    width: 100%;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    span {
      color: #252934;
      height: 24px;
      // width: 112px;
      font-family: PingFangSC-Medium;
      font-size: 16px;
      line-height: 24px;
      cursor: pointer;
    }
  }
  &-date {
    width: 100%;
    height: 16px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 34px;
    .left {
      font-size: 12px;
      color: #6b798e;
    }
    .right {
      margin-left: 18px;
    }
    .tooltip-p {
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  &-echarts {
    
  }
}
</style>

<style lang="scss">
.ranking {
  .el-radio-button__inner {
    padding: 6px 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
  }
}
</style>